﻿#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN
using System;
using System.Runtime.InteropServices;
using UnityEngine;

namespace Local {
    /// <summary>
    /// 游戏窗口设置
    /// </summary>
    public class GameScreenAdaptive {
        // GetSystemMetrics实际获取的是系统记录的分辨率，不是物理分辨率，如屏幕2560*1600，显示缩放200%，这里获取到的是1280*800
        [DllImport("user32.dll", SetLastError = true)]
        static extern int GetSystemMetrics(int nIndex);

        const int SM_CXSCREEN = 0; //主屏幕分辨率宽度
        const int SM_CYSCREEN = 1; //主屏幕分辨率高度
        const int SM_CYCAPTION = 4; //标题栏高度
        const int SM_CXFULLSCREEN = 16; //最大化窗口宽度（减去任务栏）
        const int SM_CYFULLSCREEN = 17; //最大化窗口高度（减去任务栏）

        /// <summary>游戏窗口最大宽度</summary>
        public static int maxGameScreenWidth = 1080;

        /// <summary>游戏窗口最大高度</summary>
        public static int maxGameScreenHeight = 1920;

        [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSplashScreen)]
        static void BeforeSplashScreen() {
            Resolution[] resolutions = Screen.resolutions;
            int maxScreenHeight = 0;
            for(int i = 0; i < resolutions.Length; i++) {
                Debug.Log($"resolutions[i].height={resolutions[i].height}");
                if(resolutions[i].height > maxScreenHeight) {
                    maxScreenHeight = resolutions[i].height;
                }
            }

            Debug.LogError("屏幕最大高度:" + maxScreenHeight);
            if(maxScreenHeight >= maxGameScreenHeight) {
                Screen.SetResolution(maxGameScreenWidth, maxGameScreenHeight, false);
                Debug.LogError($"设置游戏分辨率.11.....{maxGameScreenWidth} x {maxGameScreenHeight}");
            } else {
                float prop = (float)maxGameScreenWidth / maxGameScreenHeight;
                //最大化窗口高度
                int y1 = GetSystemMetrics(SM_CYFULLSCREEN);
                Debug.LogError("窗口高度:" + y1);
                //
                // // 标题栏高度
                int title = GetSystemMetrics(SM_CYCAPTION);
                Debug.Log("任务栏高度:" + title);
                //上下留出间距·方便窗口拖动
                maxScreenHeight = y1 - title;
                Debug.Log("剩余高度:" + maxScreenHeight);
                var curWidth = maxScreenHeight * prop;
                Screen.SetResolution((int)curWidth, maxScreenHeight, false);
                Debug.LogError($"设置游戏分辨率.22.....{(int)curWidth} x {maxScreenHeight}");
            }
        }
    }
}
#endif
